package com.amumu.netctoss.util;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Random;

public class CheckCodeUtil {
	private InputStream inputStream;
	private int WIDTH = 70;
	private int HEIGHT = 30;
	private String code;

	public CheckCodeUtil() {
		createImage();
	}

	private void createImage() {
		BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
		Graphics g = image.getGraphics();
		Random r = new Random();
		// g.setColor(getRandomColor());
		g.fillRect(0, 0, WIDTH, HEIGHT);
		g.setColor(Color.GRAY);
		g.drawRect(0, 0, WIDTH - 1, HEIGHT - 1);
		String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
		StringBuffer buf = new StringBuffer();
		g.setFont(new Font(null, Font.BOLD | Font.ROMAN_BASELINE | Font.ITALIC, 21));
		g.setColor(getRandomColor());
		for (int i = 0; i < 4; i++) {
			String num = String.valueOf(str.charAt(r.nextInt(str.length())));
			buf.append(num);
			g.setColor(getRandomColor());
			g.drawString(num, WIDTH / 4 * i + 1, 24);
		}

		this.code = buf.toString();

		for (int i = 0; i < 8; i++) {
			g.setColor(getRandomColor());
			g.drawLine(r.nextInt(WIDTH), r.nextInt(HEIGHT), r.nextInt(WIDTH), r.nextInt(HEIGHT));

		}
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		try {
			javax.imageio.ImageIO.write(image, "jpeg", os);
		} catch (IOException e) {
			e.printStackTrace();
		}
		ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray());
		inputStream = is;
	}

	public static Color getRandomColor() {
		Random ran = new Random();
		Color color = new Color(ran.nextInt(256), ran.nextInt(256), ran.nextInt(256));
		return color;
	}

	public InputStream getInputStream() {
		return inputStream;
	}

	public String getCode() {
		return code;
	}

}
